/*
 * Copyright (C) 2018 Zhejiang xiaominfo Technology CO.,LTD.
 * All rights reserved.
 * Official Web Site: http://www.xiaominfo.com.
 * Developer Web Site: http://open.xiaominfo.com.
 */

package com.github.xiaoymin.gateway.repository;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.github.xiaoymin.gateway.core.RouteRepository;
import com.github.xiaoymin.gateway.core.ext.PoolingConnectionManager;
import com.github.xiaoymin.gateway.core.pojo.ServiceRoute;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author <a href="mailto:xiaoymin@foxmail.com">xiaoymin@foxmail.com</a>
 * 2020/11/16 22:36
 * @since:servlet-gateway-spring-boot-starter 1.0
 */
public abstract class AbsctractRepository extends PoolingConnectionManager implements RouteRepository {

    protected final Map<String, ServiceRoute> routeMap=new HashMap<>();

    /**
     * 校验当前路由规则是否符合
     * @param serviceRoute 路由实例
     * @param servletRequest 请求对象
     * @return 是否符合规则
     */
    protected boolean checkRoute(ServiceRoute serviceRoute,HttpServletRequest servletRequest){
        boolean flag=false;
        if (serviceRoute!=null){
            switch (serviceRoute.getMode()){
                case ROUTE_MODE_HEADER:
                    String value=servletRequest.getHeader(ROUTE_MODE_HEADER_NAME);
                    flag=StrUtil.equalsIgnoreCase(value,serviceRoute.getValue());
                    break;
                case ROUTE_MODE_PREFIX:
                    flag=servletRequest.getRequestURI().startsWith(serviceRoute.getValue());
                    break;
                case ROUTE_MODE_SUFFIX:
                    flag=servletRequest.getRequestURI().endsWith(serviceRoute.getValue());
                    break;

            }
        }
        return flag;
    }
    @Override
    public List<ServiceRoute> getRoutes() {
        return CollectionUtil.newArrayList(routeMap.values());
    }


    @Override
    public boolean checkRouteProxy(HttpServletRequest httpServletRequest) {
        return false;
    }
}
